package com.lagou.edu.homework.controller;

import com.lagou.edu.homework.service.EmailFeignClient;
import com.lagou.edu.homework.service.LagouAuthCodeService;
import com.lagou.edu.homework.service.UserFeignClient;
import com.lagou.edu.pojo.LagouAuthCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/code")
@Slf4j
public class CodeController {

    @Autowired
    private EmailFeignClient emailFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private LagouAuthCodeService authCodeService;

    /**
     * 生成验证码并发送到对应邮箱
     *
     * @param email
     * @return
     */
    @GetMapping("/create/{email}")
    public Boolean create(@PathVariable String email) {
        // 判断用户是否已经注册
        Boolean registered = userFeignClient.isRegistered(email);
        if (registered) {
            return false;
        }

        // 获取当前是否有验证码是一分钟内发送的
        Boolean isExpire = authCodeService.validateByEmail(email);
        if (isExpire) {
            return false;
        }
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        boolean sendRes = emailFeignClient.sendEmail(email, code);
        if (sendRes) {
            LagouAuthCode authCode = new LagouAuthCode();
            authCode.setEmail(email);
            authCode.setCode(code);
            authCode.setCreatetime(System.currentTimeMillis());
            authCode.setExpiretime(System.currentTimeMillis() + 10 * 60 * 1000);
            return authCodeService.saveAuthCode(authCode);
        }
        return false;
    }

    /**
     * 校验验证码
     *
     * @param email
     * @return
     */
    @GetMapping("/validate/{email}/{code}")
    public Boolean validate(@PathVariable String email, @PathVariable String code) {
        return authCodeService.validateEmailAndCode(email, code);
    }

}
